// pages/indexnew/indexnew.js
var Bmob = require('../../dist/Bmob-1.6.0.min.js');
var app = getApp()
const {
  $Message
} = require('../../dist/base/index');
var utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorArr: ["blue", "green", "red", "pink", "yellow"],
    randomColor: [],
    autoplay: true,
    interval: 3500,
    duration: 1500,
    swiperCurrent: 0,
    flag: false,
    swiperIndex: 0,
    animation1: '',
    animation2: '',
    animation3: '',
    time: '',



    imgUrls: [{
        url: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg'
      },

      {
        url: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg'
      },

      {
        url: 'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
      },

    ],
    array: []

  },
  detailPage: function(e) {
    console.log(e.currentTarget.id)
    //这个大概是点了一下那个详情
    wx.navigateTo({
      url: '../../pages/detail/detail?objectId=' + e.currentTarget.id
    })
  },
  userPage: function(e) {
    console.log(e.currentTarget.id)
    //这个是点了头像或者昵称那行
    wx.navigateTo({
      url: '../../pages/idcard/idcard?objectId=' + e.currentTarget.id
    })
  },

  add: function() {
    //点了一下那个大大的绿绿的按钮，跳转到添加信息界面
    wx.navigateTo({
      url: '../../pages/input/input'
    })
  },
  jumpTo: function(e) {
    console.log("你按下了三个大按钮中的", e.currentTarget.id)
    wx.navigateTo({
      url: '../../pages/inner/inner?id=' + e.currentTarget.id
    })
  },
  //用按钮方式获取用户授权？
  getUserInfo: function(e) {
    console.log('getUserInfo', e.detail.userInfo)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  swiperchange: function(e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  getLabelColor: function() {
    let that = this
    var colorLen = this.data.colorArr.length;
    var arrLen = this.data.array.length;
    var colorArr = this.data.colorArr;
    var newArr = [];
    var newcolorArr = [];
    var pre = null;
    for (var i = 0; i < arrLen; i++) {
      newcolorArr = [];
      if (that.data.array[i] == undefined)
        return;
      for (var j = 0; j < that.data.array[i].tag.length; j++) {
        while (random == pre) {
          var random = colorArr[Math.floor(Math.random() * colorLen)];
        }
        pre = random;
        newcolorArr.push(random);
      }

      newArr.push(newcolorArr);
    }
    this.setData({
      randomColor: newArr
    })
  },
  refresh: function() {
    let that = this
    console.log('index.js:onLoad')
    //把颜色随机好待用
    that.getLabelColor()
    //去数据库把帖子都拿出来 顺便把帖子的作者拿出来
    var list = []
    var temp = {}
    let createdAt
    //查找帖子数据
    const query = Bmob.Query("Postings");
    query.include('user', 'post')
    // query.descending("createdAt")
    query.order('-createdAt');
    query.find().then(res => {
      var array = new Array(res.length)
      for (let i = 0; i < res.length; i++) {
        var label_list;
        //查找tags

        const query1 = Bmob.Query("label")
        query1.statTo("where", '{"$relatedTo":{"object":{"__type":"Pointer","className":"Postings","objectId":"' + res[i].objectId + '"},"key":"tag"}}');

        // query1.statTo("where", '{"tag":{"$inQuery":{"where":{"tag":"乒乓球"},"className":"label"}}}');
        query1.find().then(res1 => {
          //时间格式化
          // createdAt = utils.time(res[i].createdAt)


          //查找UserData
          const pointer = Bmob.Pointer('_User')
          const poiID = pointer.set(res[i].user.objectId)

          const query = Bmob.Query('UserData')
          query.include('major', 'post')
          query.equalTo("user", "==", poiID);
          query.find().then(res2 => {
            label_list = []
            for (var j = 0; j < res1.length; j++) {
              label_list.push(res1[j].tag);
            }
            //把帖子的数据存入list
            list = that.data.array
            if (res2.length) {
              //如果服务器有UserData
              temp = {
                objectid: res[i].objectId,
                title: res[i].title,
                user: res[i].user,
                name: res2[0].nickName,
                imageurl: res2[0].userPic.url,
                content: res[i].detail,
                tag: label_list,
                createdAt: utils.time(res[i].createdAt)
              }
            } else {
              temp = {
                //如果服务器没有UserData
                objectid: res[i].objectId,
                title: res[i].title,
                user: res[i].user,
                name: res[i].user.nickName,
                imageurl: res[i].user.userPic,
                content: res[i].detail,
                tag: label_list,
                createdAt: utils.time(res[i].createdAt)
              }

            }
            array[i] = temp
            // list.push(temp)
            that.setData({
              array: array
            })
            that.getLabelColor()
            wx.hideLoading()

          })
          // console.log(that.data.array)
        }).catch(err => {
          console.log(err)
          wx.hideLoading()
        })
      }
    }).catch(err => {
      wx.hideLoading()
      $Message({
        content: '获取服务器信息失败',
        type: 'error'
      });
      console.log(err)
    })

  },


  onLoad: function(options) {
    let that = this
    console.log('index.js:onLoad')
    wx.showLoading()


    //如果登陆成功则跳出登陆成功的提示~
    if (app.globalData.isLogin && !app.globalData.isLoginShowed) {
      $Message({
        content: '登陆成功',
        type: 'success'
      });
      app.globalData.isLoginShowed = true
    }
    that.refresh()


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  //点击动画目前仅针对自己写的卡片才有效
  click1: function() {

    this.animation1 = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
      transformOrigin: 'center',
      success: function(res) {
        console.log(res)
      }
    })
    this.animation1.backgroundColor('#A9A9A9').step().backgroundColor('white').step()
    this.setData({
      animation1: this.animation1.export()
    })

    console.log('index.js:onReady')

  },
  click2: function() {

    this.animation2 = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
      transformOrigin: 'center',
      success: function(res) {
        console.log(res)
      }
    })
    this.animation2.backgroundColor('#A9A9A9').step().backgroundColor('white').step()
    this.setData({
      animation2: this.animation2.export()
    })

    console.log('index.js:onReady')

  },
  click3: function() {

    this.animation3 = wx.createAnimation({
      duration: 150,
      timingFunction: 'linear',
      transformOrigin: 'center',
      success: function(res) {
        console.log(res)
      }
    })
    this.animation3.backgroundColor('#A9A9A9').step().backgroundColor('white').step()
    this.setData({
      animation3: this.animation3.export()
    })

    console.log('index.js:onReady')

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("onShow")
    this.refresh()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      randomColor: [],
      array: []
    })
    this.refresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  containerTap: function(res) {
    var that = this
    var x = res.touches[0].pageX;
    var y = res.touches[0].pageY + 85;
    this.setData({
      rippleStyle: ''
    });
    setTimeout(function() {
      that.setData({
        rippleStyle: 'top:' + y + 'px;left:' + x + 'px;-webkit-animation: ripple 0.4s linear;animation:ripple 0.4s linear;'
      });
    }, 200)
  },
})